import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo, getDetialById } from '@/api/user'
import { resetRouter } from '@/router'

const state = {
  token: getToken() || '',
  userInfo: null
}
const mutations = {
  setToken(state, data) {
    setToken(data)
    state.token = data
  },
  setInfo(state, data) {
    state.userInfo = data
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  removeInfo(state) {
    state.userInfo = null
  }
}
const actions = {
  // 1.当前仓库的实例 , 2.调用时的传参
  // 第一个login是action的属性  第二个login是引入的封装axios的API
  // 下面写法等同于: login:async function(store, data)
  async login(store, data) {
    const res = await login(data)
    localStorage.setItem('loginTime', Date.now())
    store.commit('setToken', res)
  },
  async getInfo(store) {
    const res = await getInfo()
    const detialById = await getDetialById(res.userId)
    store.commit('setInfo', {
      ...res,
      ...detialById
    })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeInfo')
    // 花裤衩封装的重置路由api
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
